module DDS_model(
	clk		, 
	rst_n		,
	key		,
	model_sel,
	Fword		,
	Pword		,
	data		
	);
	
	input 				clk		; 
	input 				rst_n		;
	input 				key		; // 同步相位
	input 	[1:0]		model_sel; // 模式选择，正弦，方波，三角
	input 	[31:0]	Fword		;// 频率控制字
	input 	[11:0]	Pword		;// 相位控制字
	output reg[13:0]	data		;

	// 同步相位
	reg key1,key2;
	always @(posedge clk ) begin
		key1 <= key;
		key2 <= key1;
	end
	
	wire en;
	assign en = !key2 & key1;
	
	// 频率控制字同步寄存器	
	reg [31:0] Fword_r;
	always @ (posedge clk ) begin
		Fword_r <= Fword;
	end
	
	// 相位控制字同步寄存器
	reg [11:0] Pword_r;
	always @ (posedge clk ) begin
		Pword_r <= Pword;
	end

	// 相位累加器
	reg [31:0] Freq_ACC;
	always @ (posedge clk or negedge rst_n) begin
		if (!rst_n)
			Freq_ACC <= 32'd0;
		else if (en)
			Freq_ACC <= 32'd0;
		else
			Freq_ACC <= Fword_r + Freq_ACC;
	end

	
//	always @ (posedge clk or negedge rst_n) begin
//		if (!rst_n)
//			Freq_ACC <= 32'd0;
//		else 
//			Freq_ACC <= Fword_r + Freq_ACC;
//	end

	// 波形数据表地址
//	wire [11:0] rom_addr;	
//	assign rom_addr = Freq_ACC[31:20] + Pword_r;

	reg [11:0] rom_addr;	

	always @ (posedge clk or negedge rst_n) begin
		if (!rst_n)
			rom_addr <= 12'd0;
		else if (en)
			rom_addr <= 12'd0;
		else
			rom_addr <= Freq_ACC[31:20] + Pword_r;
	end


	wire [13:0] data_sin, data_squ, data_tri;
	
	// 正弦波
	sin_rom	sin_rom_inst (
		.address ( rom_addr ),
		.clock 	( clk ),
		.q 		( data_sin )
	);
	// 方波
	squ_rom	squ_rom_inst (
		.address ( rom_addr ),
		.clock 	( clk ),
		.q 		( data_squ )
	);
	// 三角波
	tri_rom	tri_rom_inst (
		.address ( rom_addr ),
		.clock 	( clk ),
		.q 		( data_tri )
	);

	always @ (*) begin
		case (model_sel)
			2'd0:data = data_sin;
			2'd1:data = data_squ;
			2'd2:data = data_tri;
			default:data = 14'd8192;
		endcase
	end

endmodule 